import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import type { App } from 'vue';
import { useUserStoreWithout } from '@/store/modules/user';
import Cookies from 'js-cookie';
import { getAdminApi } from '@/request/admin';
const useStore = useUserStoreWithout();
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login/index.vue'),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
router.beforeEach(async (to, from, next) => {
  const token = Cookies.get('token');
  const menu = useStore.menus;
  if (token && menu.length === 0) {
    let res = await getAdminApi();
    if (res.code == 200) {
      useStore.updataMenus(res.data.menus);
      const newMenu = useStore.getMenusConf;
      for (let key in newMenu) {
        let routeObj: RouteRecordRaw = {
          path: '/' + newMenu[key].name,
          name: newMenu[key].name,
          component: () => import('../views/Home/index.vue'),
          children: [],
        };
        newMenu[key].list?.forEach((submenu) => {
          routeObj.children!.push({
            path: submenu.name,
            name: submenu.name,
            component: () =>
              import(`@/views/${newMenu[key].name}/${submenu.name}.vue`),
          });
        });
        router.addRoute(routeObj);
      }
      router.addRoute({
        path: '/',
        name: 'home',
        component: () => import('@/views/Home/index.vue'),
        redirect: '/index',

        children: [
          {
            path: 'index',
            name: 'index',
            component: () => import('@/views/Index/index.vue'),
          },
        ],
      });
      return next(to);
    } else {
      Cookies.remove('token');
      return next('/login');
    }
  } else if (!token && to.path !== '/login') {
    return next('/login');
  } else if (token && to.path == '/login') {
    return next(from);
  } else {
    next();
  }
});
export const initRouter = (app: App<Element>) => {
  app.use(router);
};
export default router;
